package com.lzp.mybatis.custom.sqlsession.proxy;

import com.lzp.mybatis.custom.config.Mapper;
import com.lzp.mybatis.custom.utils.Executor;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.util.Map;

/**
 * Mapper代理对象
 */
public class MapperProxy implements InvocationHandler {
    // key为全限定类名+方法名，value为Mapper对象
    private Map<String, Mapper> mappers;

    //
    private Connection conn;

    public MapperProxy(Map<String, Mapper> mappers, Connection conn) {
        this.mappers = mappers;
        this.conn = conn;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        // 获取方法名
        String methodName = method.getName();
        // 获取方法所在类名
        String className = method.getDeclaringClass().getName();
        // 组合key值
        String key = className + "." + methodName;
        // 获取Mapper对象
        Mapper mapper = mappers.get(key);
        // mapper空检验
        if(mapper == null) {
            throw new IllegalArgumentException("参数异常");
        }
        // 调Executor类，执行sql语句，封装结果集
        return new Executor().selectList(mapper, conn);
    }
}
